import axios from "axios";
import { useUserStore } from "@/stores/modules/user";
/**
 * 加密Http 的 Headers
 */
function useEncryptConfig() {
  const { token, secret } = useUserStore();
  const setToken = (config) => {
    if (token) {
      config.headers["X-AUTH-TOKEN"] = token;
    }
    return config;
  };
  const setSecret = (config) => {
    if (secret) {
      config.headers["X-AUTH-SIGN"] = secret;
    }
    return config;
  };
  const encryptConfig = (config) => {
    return setSecret(setToken(config));
  };
  return { encryptConfig };
}

const BASE_OPTIONS = {
  baseURL: "",
  timeout: 1000 * 5,
};

const service = axios.create(BASE_OPTIONS);

// 添加请求拦截器
service.interceptors.request.use(
  function (config) {
    const { encryptConfig } = useEncryptConfig();
    return encryptConfig(config);
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  function (response) {
    const {
      status,
      data: { code, data },
    } = response;

    if (status === 200 && code === 0) {
      return data;
    }

    return Promise.reject(response.data);
  },
  function (error) {
    console.log("【error】", response);

    return Promise.reject(error);
  }
);

export default service;

/**
 * axios post请求
 * @returns
 */
export function PostHttp$(url, data, options = {}) {
  return service.post(url, data, options);
}
